package com.cuijq.virwallet.repository;

import com.cuijq.virwallet.repository.entity.VirtualWalletEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Repository
public class VirtualWalletRepository {

    @Autowired
    BaseDao baseDao;

    public VirtualWalletEntity getWalletEntity(Long walletId) {
        Optional<VirtualWalletEntity> byId = baseDao.findById(walletId);
        return byId.get();
    }

    public BigDecimal getBalance(Long walletId) {
        VirtualWalletEntity walletEntity = getWalletEntity(walletId);
        return walletEntity.getBalance();
    }

    /**
     * 出帐
     *
     * @param walletId
     * @param subtract
     */
    public void updateBalance(Long walletId, BigDecimal subtract) {
        VirtualWalletEntity virtualWalletEntity = new VirtualWalletEntity();
        virtualWalletEntity.setId(walletId);
        virtualWalletEntity.setBalance(subtract);
        baseDao.save(virtualWalletEntity);
    }

    public List<VirtualWalletEntity> findAll() {
        return baseDao.findAll();
    }

    public void save(VirtualWalletEntity virtualWalletEntity) {
        if (virtualWalletEntity!=null && !StringUtils.isEmpty(virtualWalletEntity.getUserName())){
            virtualWalletEntity.setCreateTime(new Date().getTime());
            virtualWalletEntity.setBalance(new BigDecimal(0));
        }
        baseDao.save(virtualWalletEntity);
    }

    public void deleteById(Long id) {
        baseDao.deleteById(id);
    }

    public Optional<VirtualWalletEntity> findOne(Example<VirtualWalletEntity> example) {
        return baseDao.findOne(example);
    }
}
